//
// Created by 11510 on 2024/6/13.
//
#include <iostream>
#include <pthread.h>
using namespace std;


class Singleton{

private:
    int _ix;
    int _iy;
    static Singleton * _pInstance;

public:
    static Singleton * getInstance(){
        /**
         * 当多线程进入if中，会造成单例对象创建多个，
         * 但是只有一个地址被保存到_pInstance，因此会造成内存泄漏
         */
        if(_pInstance == nullptr){
//            程序结束时自动调用destroy()
            atexit(destroy);
            _pInstance = new Singleton(0, 0);
        }
        return _pInstance;
    }


    void init(int x,int y){
        _ix = x;
        _iy = y;
    }

    void print(){
        cout << "(" << this->_ix
             << "," << this->_iy
             << ")" << endl;
    }

    static void destroy(){
        if(_pInstance){
            delete _pInstance;
            _pInstance = nullptr;
        }
    }


private:

    Singleton() = default;//C++11

    Singleton(int x,int y): _ix(x), _iy(y){
        cout << "Singleton(int,int)" << endl;
    }

    ~Singleton(){
        cout << "~Singleton()" << endl;
    }

    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;


};
/**
 * 饱汉式：懒加载，要用到时候再创建，线程不安全
 */
//Singleton * Singleton::_pInstance = nullptr;

/**
 * 饿汉式：最开始就把对象创建，能够确保这里的getInstance是第一次被调用，线程安全
 * 这里一定会走到if (_pInstance == nullptr)里 static区默认存0/NULL
 */
Singleton*Singleton::_pInstance = Singleton::getInstance();


void test0(){
    Singleton::getInstance()->init(2, 9);
    Singleton::getInstance()->print();
//    此处不会double free
    Singleton::destroy();
}

int main(void) {
    test0();
    return 0;
}
